package com.ocom.company.controller;

import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.master.EntityCompanyPart;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.SetUnitParaRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.company.*;
import com.ocom.company.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/4/4
 **/
@Slf4j
@RestController
public class ShouHouController {


	@Autowired
	private CompanyPartService companyPartService;

	@Autowired
	private CompanyInfoService companyInfoService;

	@Autowired
	private CompanyListInfoService companyListInfoService;

	@Autowired
	private PersonnelInfoService personnelInfoService;

	@Autowired
	private XfDeviceInfoService xfDeviceInfoService;

	@Autowired
	private MjDeviceInfoService mjDeviceInfoService;

	@Autowired
	private XfMerchPayInfoService xfMerchPayInfoService;

	/**
	 * 5.2获取单位当前数据（getUnitCurrentData）
	 */
	@PostMapping(CompanyServiceUrl.URL_getUnitCurrentData)
	public Result getUnitCurrentData(Integer subDb) {
		//从分库2.2.2人员信息表personnel_info获取当前用户数：
		//获取库单位Id
		EntityCompanyPart entityCompanyPart = companyPartService.getDataSourceComId(subDb);
		if (entityCompanyPart == null) {
			return ResultUtil.error(ResultEnum.Err_3075);
		}
		Long comId = entityCompanyPart.getBeginComId();


		List<EntityCompanyInfo> companyList = companyInfoService.getCompanyList(comId);

		/**
		 * comId	单位ID	Int
		 * nowUserNum	当前用户数	int	默认填0
		 * nowXfMachNum	当前消费设备数	int	默认填0
		 * nowMjMachNum	当前门禁设备数	int	默认填0
		 * nowTableNum	当前取餐点数	int	默认填0
		 * xfRecNum	上月消费记录数	int	默认填0
		 * mjRecNum	上月门禁记录数	int	默认填0
		 */
		//1、从分库2.2.2人员信息表personnel_info获取当前用户数：
		List<PersonCountVo> personCountVos = personnelInfoService.selectPerCount(comId);
		//list转map
		Map<Long, Integer> personCountMap = personCountVos.stream().collect(Collectors.toMap(e -> e.getComId(),
				e -> e.getNowUserNum(),
				(e1, e2) -> e1));

		//2、从分库2.3.9设备信息表xf_device_info获取当前消费设备数：
		List<MachCountVo> machCountVos = xfDeviceInfoService.selectMachCount(comId);
		//list转map
		Map<Long, Integer> machCountMap = machCountVos.stream().collect(Collectors.toMap(e -> e.getComId(),
				e -> e.getNowXfMachNum(),
				(e1, e2) -> e1));

		//3、从分库2.4.1.1门禁设备mj_device_info获取当前门禁设备数：
		List<MjMachCountVo> mjMachCountVos = mjDeviceInfoService.selectMjMachCount(comId);
		//list转map
		Map<Long, Integer> mjMachCountMap = mjMachCountVos.stream().collect(Collectors.toMap(e -> e.getComId(),
				e -> e.getNowMjMachNum(),
				(e1, e2) -> e1));

		//4、从分库2.3.32取餐地址信息表receipt_address获取当前取餐点数：

		//5、从分库2.3.23商户统一支付信息xf_merch_pay_info获取当前支付通道数：
		List<MerchPayCountVo> merchPayCountVos = xfMerchPayInfoService.selectMerchPayCount(comId);
		//list转map
		Map<Long, Integer> merchPayCountMap = merchPayCountVos.stream().collect(Collectors.toMap(e -> e.getComId(),
				e -> e.getNowChannelNum(),
				(e1, e2) -> e1));

		List<UnitCurrentDataVo> list = new ArrayList<>();
		for (EntityCompanyInfo entityCompanyInfo : companyList) {
			UnitCurrentDataVo unitCurrentDataVo = new UnitCurrentDataVo();
			unitCurrentDataVo.setComId(entityCompanyInfo.getComId());
			unitCurrentDataVo.setComName(entityCompanyInfo.getComName());
			if (personCountMap.containsKey(entityCompanyInfo.getComId())) {
				unitCurrentDataVo.setNowUserNum(personCountMap.get(entityCompanyInfo.getComId()));
			}
			if (machCountMap.containsKey(entityCompanyInfo.getComId())) {
				unitCurrentDataVo.setNowXfMachNum(machCountMap.get(entityCompanyInfo.getComId()));
			}
			if (mjMachCountMap.containsKey(entityCompanyInfo.getComId())) {
				unitCurrentDataVo.setNowMjMachNum(mjMachCountMap.get(entityCompanyInfo.getComId()));
			}
			if (merchPayCountMap.containsKey(entityCompanyInfo.getComId())) {
				unitCurrentDataVo.setNowChannelNum(merchPayCountMap.get(entityCompanyInfo.getComId()));
			}
			list.add(unitCurrentDataVo);
		}
		return ResultUtil.success(list);
	}

//	/**
//	 * 5.3获取单位月数据（getUnitMonthData）
//	 */
//	@PostMapping(CompanyServiceUrl.URL_getUnitMonthData)
//	public Result getUnitMonthData(@RequestBody GetMngUserInfoVo getMngUserInfoVo){
//		return ResultUtil.success();
//	}

	/**
	 * 5.4修改单位使用权限（setUnitPara）
	 */
	@PostMapping(CompanyServiceUrl.URL_setUnitPara)
	public Result setUnitPara(@RequestBody SetUnitParaRequest request) {
		EntityCompanyList entityCompanyList = new EntityCompanyList();
		entityCompanyList.setComId(request.getComId());

		/**
		 * Integer comId;
		 * Integer saasNo;
		 * 	Integer xfVer;
		 * 	Integer mjVer;
		 * 	Integer comStatus;
		 * 	String endTime;
		 * 	Integer maxUserNum;
		 * 	Integer maxXfMachNum;
		 * 	Integer maxMjMachNum;
		 * 	Integer maxTableNum;
		 * 	Integer maxchannelNum;
		 */
		if (request.getSaasNo() != null) {
//			entityCompanyList.setSaasNo(request.getSaasNo().toString());
			entityCompanyList.setSaasId(request.getSaasNo().longValue());
		}
		if (request.getXfVer() != null) {
			entityCompanyList.setXfStatus(request.getXfVer());
		}
		if (request.getMjVer() != null) {
			entityCompanyList.setMjStatus(request.getMjVer());
		}
		if (request.getComStatus() != null) {
			entityCompanyList.setComStatus(request.getComStatus().longValue());
		}
		try {
			if (!CommonUtil.isNull(request.getEndTime())) {
				entityCompanyList.setEndTime(DateUtils.strToDate2(request.getEndTime()));
			}
		} catch (Exception e) {
			log.info("时间转换失败 【{}】【{}】", request, e);
		}
		if (request.getMaxUserNum() != null) {
			entityCompanyList.setMaxUserNum(request.getMaxUserNum());
		}
		if (request.getMaxXfMachNum() != null) {
			entityCompanyList.setMaxXfMachNum(request.getMaxXfMachNum());
		}
		if (request.getMaxMjMachNum() != null) {
			entityCompanyList.setMaxMjMachNum(request.getMaxMjMachNum());
		}
		if (request.getMaxTableNum() != null) {
			entityCompanyList.setMaxTableNum(request.getMaxTableNum());
		}
		if (request.getMaxChannelNum() != null) {
			entityCompanyList.setMaxChannelNum(request.getMaxChannelNum());
		}
		companyListInfoService.updateCompanyListById(entityCompanyList);
		return ResultUtil.success();
	}

	/**
	 * 5.5获取分库当前数据（getSubDbCurrentData）
	 */
	@PostMapping(CompanyServiceUrl.URL_getSubDbCurrentData)
	public Result getSubDbCurrentData(Integer subDb) {

		//从分库2.2.2人员信息表personnel_info获取当前用户数：
		//获取库单位Id
		EntityCompanyPart entityCompanyPart = companyPartService.getDataSourceComId(subDb);
		if (entityCompanyPart == null) {
			return ResultUtil.error(ResultEnum.Err_3075);
		}
		Long comId = entityCompanyPart.getBeginComId();

//		List<EntityCompanyInfo> companyList = companyInfoService.getCompanyList(comId);


		SubDbCurrentDataVo dataVo = new SubDbCurrentDataVo();

		/**
		 * 1、根据subDb计算com_id起止范围com_id1、com_id2，从总库1.2单位列表company_list获取当前单位数：
		 * select 	com_status ,  count(com_id)
		 * from 	company_list
		 * where 	is_agent = 0 	and 	com_id between(@com_id1 , @com_id2 )
		 * group by 	com_status
		 */

		List<ComStatusCountVo> comStatusCountVos = companyListInfoService.getCompanyList(entityCompanyPart.getBeginComId(), entityCompanyPart.getEndComId());

		Integer comSum = comStatusCountVos.stream().collect(Collectors.summingInt(ComStatusCountVo::getNowComNum));
		dataVo.setUnitTotal(comSum);

		//list转map
		Map<Integer, Integer> comStatusCountMap = comStatusCountVos.stream().collect(Collectors.toMap(e -> e.getComStatus(),
				e -> e.getNowComNum(),
				(e1, e2) -> e1));
		//0正常，1演示，2试用，10逾期，11停用
		if (comStatusCountMap.containsKey(0)) {
			dataVo.setNormalUnit(comStatusCountMap.get(0));
		}
		if (comStatusCountMap.containsKey(1)) {
			dataVo.setSampleUnit(comStatusCountMap.get(1));
		}
		if (comStatusCountMap.containsKey(2)) {
			dataVo.setTestUnit(comStatusCountMap.get(2));
		}
		if (comStatusCountMap.containsKey(10)) {
			dataVo.setOverUnit(comStatusCountMap.get(10));
		}
		if (comStatusCountMap.containsKey(11)) {
			dataVo.setStopUnit(comStatusCountMap.get(11));
		}

		dataVo.setNowUserNum(personnelInfoService.selectCount(comId));
		dataVo.setNowMjMachNum(mjDeviceInfoService.selectCount(comId));
		dataVo.setNowXfMachNum(xfDeviceInfoService.selectCount(comId));
		return ResultUtil.success(dataVo);
	}


//	/**
//	 * 5.6获取分库月数据（getSubDbMonthData）
//	 */
//	@PostMapping(CompanyServiceUrl.URL_getSubDbMonthData)
//	public Result getSubDbMonthData(@RequestBody GetMngUserInfoVo getMngUserInfoVo){
//		return ResultUtil.success();
//	}

	/**
	 * //5.7获取分库的单位范围（getSubDbComId）
	 */
	@PostMapping(CompanyServiceUrl.URL_getSubDbComId)
	public Result getSubDbComId(Integer subDb) {
		//从分库2.2.2人员信息表personnel_info获取当前用户数：
		//获取库单位Id
		if (subDb > 0) {
			EntityCompanyPart entityCompanyPart = companyPartService.getDataSourceComId(subDb);
			if (entityCompanyPart == null) {
				return ResultUtil.error(ResultEnum.Err_3075);
			}
			return ResultUtil.success(entityCompanyPart);
		} else {
			return ResultUtil.success(companyPartService.getDataSourceList());
		}


	}


}
